﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using YSC__RestClient.BLL.Helper;
using YSC_Core.BLL.Domain.CommonModels;
using YSC_Core.BLL.Domain.Utils;
using YSC_Services.BLL.Services.Interfaces;

namespace YSC_App_WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadFileController : ControllerBase
    {
        private readonly IHostingEnvironment _rep;

        private readonly IBasisBackstageServices _basisBackstage;
        string[] pictureFormatArray = { "png", "jpg", "jpeg", "bmp", "gif", "ico", "PNG", "JPG", "JPEG", "BMP", "GIF", "ICO" };
        public UploadFileController(IHostingEnvironment rep, IBasisBackstageServices basisBackstage)
        {
            this._rep = rep;
            this._basisBackstage = basisBackstage;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadFile")]
        public async Task<IActionResult> UploadFile()
        {

            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);

            //size > 100MB refuse upload !
            if (size > 104857600)
            {
                return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("pictures total size > 100MB , server refused !"));
            }

            List<string> filePathResultList = new List<string>();

            foreach (var file in files)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                string filePath = _rep.WebRootPath + $@"\Files\Pictures\";

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                string suffix = fileName.Split('.')[1];

                if (!pictureFormatArray.Contains(suffix))
                {
                    return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("the picture format not support ! you must upload files that suffix like 'png','jpg','jpeg','bmp','gif','ico'."));
                }

                fileName = Guid.NewGuid() + "." + suffix;

                string fileFullName = filePath + fileName;

                using (FileStream fs = System.IO.File.Create(fileFullName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                filePathResultList.Add($"/Files/Pictures/{fileName}");
            }

            string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!";

            return Ok(Return_Helper_DG.Success_Msg_Data_DCount_HttpCode(message, filePathResultList, filePathResultList.Count));
        }

        /// <summary>
        /// 后台上传
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("UploadFileBackstage")]
        public async Task<IActionResult> UploadFileBackstage(string bllId, string bllType, string type, int typeInt = 0)
        {
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);


            var model = new YSC_Core.BLL.Domain.BackstageModels.MediaImageModel()
            {
                BllId = bllId,
                BllType = bllType,
                Type = type,
                TypeInt = typeInt
            };
            try
            {
                //size > 100MB refuse upload !
                if (size > 104857600)
                {
                    return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("pictures total size > 100MB , server refused !"));
                }

                List<string> filePathResultList = new List<string>();

                foreach (var file in files)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                    string filePath = _rep.WebRootPath + $@"\Files\Pictures\";

                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    int index = fileName.LastIndexOf('.');
                    //从下一个索引开始截取
                    string suffix = fileName.Substring(index + 1);
                   // string suffix = fileName.Split('.')[2];

                    if (!pictureFormatArray.Contains(suffix))
                    {
                        return Ok(Return_Helper_DG.Error_Msg_Ecode_Elevel_HttpCode("the picture format not support ! you must upload files that suffix like 'png','jpg','jpeg','bmp','gif','ico'."));
                    }

                    fileName = Guid.NewGuid() + "." + suffix;

                    string fileFullName = filePath + fileName;

                    using (FileStream fs = System.IO.File.Create(fileFullName))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    filePathResultList.Add($"/Files/Pictures/{fileName}");
                }

                string message = $"{files.Count} file(s) /{size} bytes uploaded successfully!";

                model.FileUrl = filePathResultList.FirstOrDefault();

                var ret = _basisBackstage.AddUpdateMediaImageUpdate(model);

                return Ok(ret);
            }
            catch
            {
                return Ok("上传出现错误");
            }



        }

        [HttpPost]
        [Route("AES_decrypt")]
        public ActionResult AES_decrypt(WXModel wx)
        {
            try
            {
                var result = AesHelper.DecryptForWeChatApplet(wx.encryptedDataStr, wx.key, wx.iv);
                YscUserWXModel wxModel = JsonConvert.DeserializeObject<YscUserWXModel>(result);
                return Ok(wxModel);
            }
            catch (Exception e)
            {
                return Ok(e);

            }

        }

        private static byte[] KCS7Encoder(int text_length)
        {
            int block_size = 32;
            // 计算需要填充的位数
            int amount_to_pad = block_size - (text_length % block_size);
            if (amount_to_pad == 0)
            {
                amount_to_pad = block_size;
            }
            // 获得补位所用的字符
            char pad_chr = chr(amount_to_pad);
            string tmp = "";
            for (int index = 0; index < amount_to_pad; index++)
            {
                tmp += pad_chr;
            }
            return Encoding.UTF8.GetBytes(tmp);
        }

        static char chr(int a)
        {

            byte target = (byte)(a & 0xFF);
            return (char)target;
        }
    }
}